<?php

namespace app\channel\model;
use app\BaseModel;
use think\facade\Cache;
use app\shop\model\GoodsModel;
use app\shop\model\GoodsSkuModel;
use app\shop\model\SkuCustomModel;

//*------------------------------------------------------ */
//-- 代理商品
/*------------------------------------------------------ */
class ChannelGoodsModel extends BaseModel
{
    protected $table = 'channel_goods';
    public  $pk = 'id';
    protected $mkey = 'channel_goods_mkey_';
    /*------------------------------------------------------ */
    //-- 清除缓存
    /*------------------------------------------------------ */
    public function cleanMemcache($goods_id = 0)
    {
        Cache::rm($this->mkey . $goods_id);
        Cache::rm($this->mkey .'prices_' . $goods_id);
        Cache::rm($this->mkey .'byshop_' . $goods_id);
    }
    /*------------------------------------------------------ */
    //-- 获取代理商品信息
    //-- $goods_id int 商品id
    /*------------------------------------------------------ */
    public function info($goods_id)
    {
        $goods = Cache::get($this->mkey . $goods_id);
        if (empty($goods)) {
            $goods = $this->where('goods_id', $goods_id)->find();
            if (empty($goods) == true) return [];
            $goods = $goods->toArray();
            Cache::set($this->mkey . $goods_id, $goods, 600);
        }

        $goods['is_on_sale'] = 0;
        if ($goods['isputaway'] == 1){
            $goods['is_on_sale'] = 1;
        }elseif ($goods['isputaway'] == 2){
            $time = time();
            //自动上下架判断
            if ($goods['added_time'] <= $time && $goods['shelf_time'] >= $time) {
                $goods['is_on_sale'] = 1;
            } elseif ($goods['shelf_time'] < $time) {
                $goods['isputaway'] = 0;
            }
        }
        $goods['convert_unit'] = json_decode($goods['convert_unit'],true);
        return $goods;
    }
    /*------------------------------------------------------ */
    //-- 获取代理商品出货信息
    //-- $goods_id int 商品id
    //-- $proxy_id int 当前代理层级上一级的层级ID
    /*------------------------------------------------------ */
    public function purchaseGoodsInfo($goods_id,$proxy_id)
    {
        $channelGoods = $this->info($goods_id);//代理商品数据

        if (empty($channelGoods)){
            return [];
        }
        $goods = $this->getShopGoods($goods_id);//商城的商品数据

        $goods['price_type'] = $channelGoods['price_type'];
        $goods['pricing_type'] = $channelGoods['pricing_type'];
        $goods['is_on_sale'] = $channelGoods['is_on_sale'];
        $goods['unit'] = $channelGoods['unit'];
        $goods['convert_unit'] = $channelGoods['convert_unit'];
        $goods['unitLits'] = (new GoodsUnitModel)->getRows();

        $prices = $this->getPrcies($goods,$proxy_id);//出货价
        if ($goods['is_spec'] == 0) {
            $goods['price'] = $prices[0]['price'];
        }else{
            if ($channelGoods['pricing_type'] == 0){ //固定价
                foreach ($goods['sub_goods'] as $key=>$sub_goods){
                    if ($channelGoods['price_type'] == 0){
                        $sub_goods['price'] = $prices[0]['price'];
                    }else{
                        $sub_goods['price'] = $prices[$sub_goods['sku_id']]['price'];
                    }
                    $goods['sub_goods'][$key] = $sub_goods;
                }
            }else{
                foreach ($goods['sub_goods'] as $key=>$sub_goods){
                    $sub_goods['price'] = $prices[$sub_goods['sku_id']]['price'];
                    $goods['sub_goods'][$key] = $sub_goods;
                }
            }
        }

        return $goods;
    }
    /*------------------------------------------------------ */
    //-- 查询商品出货价
    //-- $goods array 商品信息
    //-- $proxy_id intval 代理层级ID
    //-- $showMini bool 是否返回最小价格，否则返回所有
    /*------------------------------------------------------ */
    public function getPrcies(&$goods,$proxy_id = 0,$showMini = false)
    {
        $mkey = $this->mkey.'prices_' . $goods['goods_id'];
        $prices = Cache::get($mkey);
        if (empty($prices)){
            $ChannelGoodsPricesModel = new ChannelGoodsPricesModel();
            $prices = $ChannelGoodsPricesModel->where('goods_id',$goods['goods_id'])->order('price ASC')->select()->toArray();
            Cache::set($mkey, $prices, 600);
        }
        //如果为折扣定价，多规格商品时获取零售价
        if ($goods['pricing_type'] == 1 && $goods['is_spec'] == 1){
            $GoodsSkuModel = new GoodsSkuModel();
            $skuPrice = $GoodsSkuModel->where('goods_id', $goods['goods_id'])->column('shop_price','sku_id');
        }

        $_prices = [];
        foreach ($prices as $key=>$price){
            if ($goods['price_type'] != $price['price_type'] || $proxy_id != $price['proxy_id']){
                continue;
            }

            if ($goods['pricing_type'] == 1){//折扣定价
                if ($goods['is_spec'] == 1){//多规格
                    if ($goods['price_type'] == 1){ //独立出价
                        $price['price'] = sprintf("%.2f",$skuPrice[$price['sku_id']] / 100 * $price['price']);
                        $_prices[$price['sku_id']] = $price;
                    }else{//统一出价
                        $price_pre = $price['price'];
                        foreach ($skuPrice as $sku_id=>$sku_price){
                            $price['price'] = sprintf("%.2f",$sku_price / 100 * $price_pre);
                            $_prices[$sku_id] = $price;
                        }
                    }
                }else{
                    $price['price'] = sprintf("%.2f",$goods['shop_price'] / 100 * $price['price']);
                    $_prices[$price['sku_id']] = $price;
                }
            }else{//固定售价
                $_prices[$price['sku_id']] = $price;
            }

        }
        if ($showMini == true){
            return reset($_prices);
        }
        return $_prices;
    }


    /*------------------------------------------------------ */
    //-- 自动上下架商品
    /*------------------------------------------------------ */
    public function autoSale()
    {
        $cache = Cache::init();
        $_redis = $cache->handler();
        $mkey = 'auto_channel_sale';
        $isLock = $_redis->setnx($mkey,time()+5);
        if ($isLock == false){
            $lock_time = $_redis->get($mkey);
            if(time()>$lock_time){
                $_redis->del($mkey);
                $isLock = $_redis->setnx($mkey,time()+5);
                if ($isLock == false) return false;
            }else{
                return false;
            }
        }
        $time = time();
        //自动上架处理
        $goods = $this->where('isputaway',2)->column('added_time','goods_id');
        foreach ($goods as $goods_id=>$added_time){
            if ($added_time <= $time){
                $this->where('goods_id',$goods_id)->update(['isputaway'=>1]);
            }
        }
        //自动下架处理
        $where = [];
        $where[] = ['isputaway','=',1];
        $where[] = ['shelf_time','>',0];
        $goods = $this->where($where)->column('shelf_time','goods_id');
        foreach ($goods as $goods_id=>$shelf_time){
            if ($shelf_time <= $time){
                $this->where('goods_id',$goods_id)->update(['isputaway'=>2]);
            }
        }
        return true;
    }
    /*------------------------------------------------------ */
    //-- 获取商品规格及子商品信息
    //-- $goods_id int 商品ID
    /*------------------------------------------------------ */
    public function getShopGoods($goods_id)
    {
        $mkey = $this->mkey.'byshop_' . $goods_id;
        $shopGoods = Cache::get($mkey);
        if (empty($shopGoods) == true){
            $GoodsModel = new GoodsModel();
            $shopGoods = $GoodsModel->where('goods_id',$goods_id)->field('brand_id,cid,brand_id,goods_id,is_spec,goods_sn,goods_name,shop_price,goods_thumb,goods_img,goods_number,goods_weight,m_goods_desc')->find();
            if (empty($shopGoods)){
                return [];
            }
            $shopGoods = $shopGoods->toArray();
            $web_path = config('config.host_path');
            $shopGoods['m_goods_desc'] = preg_replace('/<img src=\"\/upload/', '<img src="' .$web_path.'/upload',$shopGoods['m_goods_desc']);
            $shopGoods['m_goods_desc'] = preg_replace('/<img/', '<img style="width:100%;height:auto;"',$shopGoods['m_goods_desc']);
            if ($shopGoods['is_spec'] == 1){
                $gsrows = (new GoodsSkuModel)->where('goods_id', $goods_id)->field('sku_id,sku,sku_val,sku_name,goods_id,goods_sn,goods_number')->order('sku_val ASC')->select()->toArray();
                $skuValArr = [];
                foreach ($gsrows as $row) {
                    $sku = $row['sku'];
                    $skuValArr[] = $row['sku_val'];
                    $shopGoods['sub_goods'][] = $row;
                }
                $skuArr = explode(':', $sku);
                $SkuCustomModel = new SkuCustomModel();
                $where = [];
                $where[] = ['id', 'IN', $skuArr];
                $shopGoods['specList'] = $SkuCustomModel->field('id,val as name,speid as pid')->where($where)->order('id ASC')->select()->toArray();
                $where = [];
                $skuValArr = join(':',$skuValArr);
                $skuValArr = explode(':', $skuValArr);
                $where[] = ['id', 'IN', $skuValArr];
                $shopGoods['specChildList'] = $SkuCustomModel->field('id,val as name,speid as pid')->where($where)->order('id ASC')->select()->toArray();
                $shopGoods['imgSkuList'] = $GoodsModel->getImgsList($goods_id,true);
            }
            $shopGoods['imgList'] = $GoodsModel->getImgsList($goods_id);
            Cache::set($mkey,$shopGoods,60);
        }

        return $shopGoods;
    }


}
